package com.lqw.vhr.task;

import com.lqw.dto.EmpDTO;
import com.lqw.dto.MailConstants;
import com.lqw.vhr.model.Employee;
import com.lqw.vhr.model.MailSendLog;
import com.lqw.vhr.service.EmployeeService;
import com.lqw.vhr.service.MailSendLogService;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

@Component
public class MailSendTask {
    @Autowired
    MailSendLogService mailSendLogService;
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    EmployeeService employeeService;
    @Scheduled(cron = "0/10 * * * * ?")
    public void mailResendTask() {
        //select * from mail_send_log where status=0 and tryTime < sysdate()
        List<MailSendLog> logs = mailSendLogService.getMailSendLogsByStatus();
        if (logs == null || logs.size() == 0) {
            return;
        }
        logs.forEach(mailSendLog->{
            if (mailSendLog.getCount() >= 3) {
                mailSendLogService.updateMailSendLogStatus(mailSendLog.getMsgId(), 2);//直接设置该条消息发送失败
            }else{
                mailSendLogService.updateCount(mailSendLog.getMsgId(), new Date());//修改尝试次数以及更新update_time
                Employee emp = employeeService.getEmployeeById(mailSendLog.getEmpId());
                EmpDTO empDTO = new EmpDTO()
                        .setDepName(emp.getDepartment().getName())
                        .setEmail(emp.getEmail())
                        .setEmpName(emp.getName())
                        .setJobLevelName(emp.getJobLevel().getName())
                        .setPosName(emp.getPosition().getName());
                rabbitTemplate.convertAndSend(MailConstants.MAIL_EXCHANGE_NAME, MailConstants.MAIL_ROUTING_KEY_NAME, empDTO, new CorrelationData(mailSendLog.getMsgId()));
            }
        });
    }
}
